﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.IO;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace Wordpress.Phone.Models
{
        public class MovieCache
        {
            private const string PATH = "movies.xml";

            private List<Movie> _items;

            public void Load()
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                if (isf.FileExists(PATH))
                {
                    using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(PATH, FileMode.OpenOrCreate, isf))
                    {

                        StreamReader sr = new StreamReader(isfs);
                        XmlSerializer s = new XmlSerializer(typeof(List<Movie>));

                        this._items = s.Deserialize(sr) as List<Movie>;
                    }
                }
                else
                {
                    this._items = new List<Movie>();
                }

                if (LoadCompleted != null)
                {
                    this.LoadCompleted(this, new EventArgs());
                }
            }

            public void Save(List<Movie> movies)
            {

                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(PATH, FileMode.OpenOrCreate, isf))
                {
                    StreamWriter sw = new StreamWriter(isfs);
                    XmlSerializer s = new XmlSerializer(typeof(List<Movie>));

                    s.Serialize(sw, movies);
                }

                if (SaveCompleted != null)
                {
                    this.SaveCompleted(this, new EventArgs());
                }
                        
            }

            public IEnumerable<Movie> Items()
            {
                return this._items;
            }

            public event EventHandler<EventArgs> LoadCompleted;

            public event EventHandler<EventArgs> SaveCompleted;
        }
    }

